﻿
using HuaJiLedger.Models.Ledger;
using HuaJiLedger.Repositorys;
using System.Collections.ObjectModel;

namespace HuaJiLedger.ViewModels.Home;

internal class AddLedgerItemViewModel : ViewModelBase
{
    private readonly LedgerItemRepository repository;

    private string inOut;
    public string InOut
    { get => inOut; set { SetProperty(ref inOut, value); } }

    private int itemType;
    public int ItemType
    { get => itemType; set { SetProperty(ref itemType, value); } }

    private double money;
    public double Money
    { get => money; set { SetProperty(ref money, value); } }

    private string note;
    public string Note
    { get => note; set { SetProperty(ref note, value); } }

    public ObservableCollection<string> TypeItems { get; set; }
    public Command EditCompleteTappedCommand { get; set; }

    public AddLedgerItemViewModel(Page page)
    {
        this.page = page;

        TypeItems = new ObservableCollection<string>(LedgerData.LedgerItemTypeStrArr);
        repository = new LedgerItemRepository();
        InOut = "0";

        EditCompleteTappedCommand = new Command(async () => await ActionEditCompleteTappedCommandAsync());
    }

    async Task ActionEditCompleteTappedCommandAsync()
    {
        if (InOut != "0" && InOut != "1")
            await page.DisplayAlert("提示", @"没有选择入账\出账", "确定");

        else if (ItemType < 0)
            await page.DisplayAlert("提示", "没有选择账目类型", "确定");

        else if (money == 0)
            await page.DisplayAlert("提示", "你确定输入了正确的金额？", "确定");

        else if (string.IsNullOrEmpty(Note))
            await page.DisplayAlert("提示", "确定不写备注吗？", "确定");

        else
        {
            var random = new Random();
            var ledgerItem = new LedgerItem
            {
                Id = $"{DateTime.Now:yyyyMMddHHmmss}{random.NextInt64():00}",
                InOut = int.Parse(InOut),
                DateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                Type = (LedgerItemType)ItemType,
                Money = Money,
                Note = Note
            };

            if (await repository.InsertLedgerItemAsync(ledgerItem) > 0)
                await Shell.Current.GoToAsync("..?isRefresh=1");
        }
    }
}
